#pragma once

#include <time.h>

class Actor;		// forward declaration

class TimedCallback {
	void (*func)(Actor *actor);		// callback
	float timeout;					// in seconds
	clock_t start;					// when the timer was created
	bool repeating;					// if set, callback will keep firing
	bool toBeRemoved;				// if set, this timed callback will not fire and be removed

public:
	TimedCallback(void (*in_func)(Actor *actor), float in_timeout, bool in_isRepeating)
		: func(in_func), timeout(in_timeout), repeating(in_isRepeating), toBeRemoved(false)
	{
		// set initial timestamp
		start = clock();
	}

	void poll(Actor *actor) {
		if (toBeRemoved) {
			return;
		}

		clock_t curr = clock();
		float secondsElapsed = (float)(curr - start) / CLOCKS_PER_SEC;

		// fire callback now that timeout has expired
		if (secondsElapsed >= timeout) {
//			printf("calling timer: %f secs elapsed\n", secondsElapsed);
			func(actor);

			if (repeating) {
				start = clock();		// reset timestamp
			} else {
				// disable callback and mark for deletion
				toBeRemoved = true;
			}
		}
	}

	void kill() {
		toBeRemoved = true;
	}

	bool isDead() {
		return toBeRemoved;
	}
};

#if 0
// deprecated

// calls func in timeout seconds from now
void createTimedCallback(void (*func)(), float timeout, bool isRepeating);

TimedCallback *getTimedCallback(size_t i);

size_t getNumTimedCallbacks();

void removeDeadCallbacks();
#endif
